package com.aglow.bluetoothspeaker.main.ui.activity;

import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.test.mock.MockContentProvider;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.actions.ibluz.manager.BluzManager;
import com.actions.ibluz.manager.BluzManagerData;
import com.actions.ibluz.manager.IAlarmManager;
import com.aglow.bluetoothspeaker.R;
import com.aglow.bluetoothspeaker.app.App;
import com.aglow.bluetoothspeaker.main.base.BaseActivity;
import com.aglow.bluetoothspeaker.main.ui.adapter.AlarmAdapter;
import com.aglow.bluetoothspeaker.main.ui.dialog.PromptDialogV2;
import com.aglow.bluetoothspeaker.model.bean.AlarmDeleteItem;
import com.aglow.bluetoothspeaker.model.bean.AlarmEditorItem;
import com.aglow.bluetoothspeaker.model.bean.AlarmSetDate;
import com.aglow.bluetoothspeaker.model.event.ConnectedStateChangedEvent;
import com.aglow.bluetoothspeaker.model.event.CustomCommandEvent;
import com.aglow.bluetoothspeaker.presenter.lisnter.OnItemDeleteListener;
import com.aglow.bluetoothspeaker.presenter.lisnter.OnSwitchCheckListener;
import com.aglow.bluetoothspeaker.utils.BluzDeviceUtils;
import com.aglow.bluetoothspeaker.utils.BluzManagerUtils;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author: chufeng
 * Email: 392044178@qq.com
 * Date: 2018/9/12 11:04
 * <p>
 * <p>
 * 注意：sdk有bug 修改闹钟数据 回复的数据不准确 需要在设置闹钟数据的时候先删除原来数据在进行修改
 */
public class AlarmActivity extends BaseActivity {


    @BindView(R.id.ib_return)
    ImageButton ibReturn;
    @BindView(R.id.linearLayout)
    LinearLayout linearLayout;
    @BindView(R.id.textView3)
    TextView textView3;
    @BindView(R.id.tv_altert)
    TextView tvAltert;
    @BindView(R.id.rv_alarm)
    RecyclerView rvAlarm;
    @BindView(R.id.ib_toset_alarm)
    ImageButton ibTosetAlarm;
    private AlarmAdapter alarmAdapter;
    private BluzManagerUtils mBluzManagerUtils;
    private PromptDialogV2 disconnectHintDialog;
    private IAlarmManager mAlarmManager;
    private List<BluzManagerData.AlarmEntry> setMcuAlarmList = new ArrayList<BluzManagerData.AlarmEntry>(); //已设置的闹钟 从终端获取的
    private List<AlarmSetDate> setDateList = new ArrayList<AlarmSetDate>(); //設置到app的數據源
    private ArrayList<Integer> getIndexGroup = new ArrayList<>();//储存获取的闹钟序列号 --不定序
    private ArrayList<Integer> arrayList = new ArrayList<>();

//    private ArrayList<Integer> saveAlarmIndex =new ArrayList<>() ;
//    private ArrayList<Integer> saveUiIndex = new ArrayList<>();

    @Override

    public int getLayoutId() {
        return R.layout.activity_alarm;
    }

    @Override
    public void onBackClick() {
        finish();
    }


    @Override
    public void initData() {
        mBluzManagerUtils = BluzManagerUtils.getInstance();
        mBluzManagerUtils.setMode(BluzManagerData.FuncMode.ALARM);
        if (mBluzManagerUtils.getIBluzManager() != null) {
            mAlarmManager = mBluzManagerUtils.getIBluzManager().getAlarmManager(new BluzManagerData.OnManagerReadyListener() {
                @Override
                public void onReady() {
                    getRefreshdata();
                    Log.i("alarm", "刷新界面");
                    alarmAdapter.notifyDataSetChanged();
                }
            });
        }


        alarmAdapter = new AlarmAdapter(this, setDateList);
        rvAlarm.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        rvAlarm.setLayoutManager(new LinearLayoutManager(this));
        ((SimpleItemAnimator) rvAlarm.getItemAnimator()).setSupportsChangeAnimations(false);
        rvAlarm.setAdapter(alarmAdapter);


    }

    @Override
    public void initView() {


    }

    /**
     * 初始化获取界面数据
     */
    private void getRefreshdata() {
//        setMcuAlarmList = mAlarmManager.getList();//获取列表
        setMcuAlarmList.clear();
        if (mAlarmManager != null) {
            for (BluzManagerData.AlarmEntry entry : mAlarmManager.getList()) {
                setMcuAlarmList.add(entry);
            }
        }
//        Log.i("打印单片机数据", "数据 = " + " " + "state = " + mAlarmManager.getList().get(0).state
//                + " " + "repeat = " + Arrays.toString(mAlarmManager.getList().get(0).repeat) + " " + "序列号 = " + mAlarmManager.getList().get(0).index);
        Log.i("abc", "size = " + setMcuAlarmList.size());
        Log.i("alarm", "mAlarmManager = " + mAlarmManager);
        Log.i("alarm", "从蓝牙获取到的列表 = " + mAlarmManager.getList());
        Log.i("alarm", "setMcuAlarmList = " + setMcuAlarmList);
        for (int i = 0; i < setMcuAlarmList.size(); i++) {
            BluzManagerData.AlarmEntry alarmEntry = setMcuAlarmList.get(i);
            int hour = alarmEntry.hour;
            int minute = alarmEntry.minute;
            int index = alarmEntry.index;
            //把闹钟序列号保存起来
            getIndexGroup.add(index);

            boolean[] repeat = alarmEntry.repeat;
            String title = alarmEntry.title;
            boolean state = alarmEntry.state;
            Log.i("alarm", "index = " + index);
            Log.i("alarm", "state = " + state);
            AlarmSetDate as = new AlarmSetDate();
            as.setMinute(minute);
            as.setHour(hour);
            as.setDate(repeat);
            as.setOpenState(state);
            as.setIndex(index);
            switch (title) {
                case "0"://铃声
                    as.setSoundState(true);
                    as.setLampState(false);
                    break;
                case "1"://灯光
                    as.setSoundState(false);
                    as.setLampState(true);
                    break;
                case "2"://铃声和灯光
                    as.setSoundState(true);
                    as.setLampState(true);
                    break;
            }
            setDateList.add(as);
        }

//        if (saveUiIndex != null && saveAlarmIndex != null) {
//            for (int i = 0; i < saveUiIndex.size(); i++) {
//                for (int k = 0; k < setDateList.size(); k++) {
//                    if (setDateList.get(k).isIndex() == saveAlarmIndex.get(i)){
//                        setDateList.add(saveUiIndex.get(i), setDateList.get(k));
//                    }
//                }
//
//            }
//        }

    }

    /**
     * 刷新数据
     */
    private void refreshIndexGroup() {
//        setMcuAlarmList = mAlarmManager.getList();//获取列表
        setMcuAlarmList.clear();
        if (mAlarmManager != null) {
            for (BluzManagerData.AlarmEntry entry : mAlarmManager.getList()) {
                setMcuAlarmList.add(entry);
            }
        }
        getIndexGroup.clear();
        for (int i = 0; i < setMcuAlarmList.size(); i++) {
            BluzManagerData.AlarmEntry alarmEntry = setMcuAlarmList.get(i);
            int index = alarmEntry.index;
            //把闹钟序列号保存起来
            getIndexGroup.add(index);
        }
    }

    /**
     * 刷新闹钟目录
     *
     * @param event
     */
    @SuppressWarnings({"unused"})
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onConnectionStateChanged(ConnectedStateChangedEvent event) {
        if (!event.isConnected()) {
            setMcuAlarmList = null;
            tvAltert.setVisibility(View.VISIBLE);
            setDateList.clear();
            alarmAdapter.notifyDataSetChanged();
            Log.i("alarm", "VISIBLE111");

            showBluetoothDisconnectDialog();
        } else {
            Log.i("base", "撤销对话框");
            if (disconnectHintDialog != null) {
                disconnectHintDialog.dismiss();
            }
        }
    }

    /**
     * 新建闹钟
     *
     * @param date
     */
    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void OnSetDate(AlarmSetDate date) {
        tvAltert.setVisibility(View.INVISIBLE);
        //开始组包发送数据
        BluzManagerData.AlarmEntry alarmEntry = new BluzManagerData.AlarmEntry();
        alarmEntry.state = true;
        alarmEntry.repeat = date.getDate();
        alarmEntry.minute = date.getMinute();
        alarmEntry.hour = date.getHour();
        alarmEntry.ringId = 1;
        alarmEntry.ringType = 3;
        arrayList.clear();
        if (arrayList != null) {
            arrayList.add(0);
            arrayList.add(1);
            arrayList.add(2);
            arrayList.add(3);
        }
        refreshIndexGroup();
        for (int i = 0; i < getIndexGroup.size(); i++) {
            if (arrayList != null) {
                if (arrayList.contains(getIndexGroup.get(i))) {
                    for (int j = 0; j < arrayList.size(); j++) {
                        if (arrayList.get(j).equals(getIndexGroup.get(i))) {
                            arrayList.remove(j);
                        }
                    }
                }
            }
        }
        alarmEntry.index = arrayList.get(0);
        //刷新界面
        date.setIndex(alarmEntry.index);
        date.setOpenState(true);
        setDateList.add(date);
        alarmAdapter.notifyDataSetChanged();
        Log.i("AlarmActivity", "新建立的闹钟index = " + alarmEntry.index);

        boolean lamp = date.isLampState();
        boolean sound = date.isSoundState();
        if (lamp && sound) {
            alarmEntry.title = "2";
        }
        if (!lamp && sound) {
            alarmEntry.title = "0";
        }
        if (lamp && !sound) {
            alarmEntry.title = "1";
        }
        //發送數據
        mAlarmManager.set(alarmEntry);

        EventBus.getDefault().removeStickyEvent(date);
    }


    /**
     * @param date 编辑闹钟
     */
    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void OnNotifyItemInfo(AlarmEditorItem date) {

        //界面显示
        int alarmIndex = date.getAlarmIndex();
        AlarmSetDate alarmSetDate = setDateList.get(alarmIndex);
        alarmSetDate.setOpenState(date.isPlayState());
        alarmSetDate.setDate(date.getDate());
        alarmSetDate.setHour(date.getHour());
        alarmSetDate.setMinute(date.getMinute());
        Log.i("notif", "lamp = " + date.isLampState());
        Log.i("notif", "sound = " + date.isSoundState());
        alarmSetDate.setSoundState(date.isSoundState());
        alarmSetDate.setLampState(date.isLampState());
        alarmAdapter.notifyDataSetChanged();
        //发送数据--蓝牙
        if (date.isPlayState()) {//发送数据 - 开启
            BluzManagerData.AlarmEntry alarmEntry = new BluzManagerData.AlarmEntry();
            Log.i("alarm", "alarmEntry = " + alarmEntry);
            alarmEntry.hour = date.getHour();
            alarmEntry.minute = date.getMinute();
            alarmEntry.repeat = date.getDate();
            alarmEntry.index = alarmSetDate.isIndex();
            alarmEntry.ringId = 1;
            alarmEntry.ringType = 3;
            Log.i("alarm", "编辑闹钟后发送给样机的闹钟序列号 = " + alarmEntry.index);
            alarmEntry.state = true;
            boolean lamp = date.isLampState();
            boolean sound = date.isSoundState();
            if (lamp && sound) {
                alarmEntry.title = "2";
            }
            if (!lamp && sound) {
                alarmEntry.title = "0";
            }
            if (lamp && !sound) {
                alarmEntry.title = "1";
            }
            mAlarmManager.remove(alarmEntry);
            mAlarmManager.set(alarmEntry);
        } else {//发送数据 - 关闭
            BluzManagerData.AlarmEntry alarmEntry = new BluzManagerData.AlarmEntry();
            Log.i("alarm", "alarmEntry = " + alarmEntry);
            alarmEntry.hour = date.getHour();
            alarmEntry.minute = date.getMinute();
            alarmEntry.repeat = date.getDate();
            alarmEntry.index = alarmSetDate.isIndex();
            alarmEntry.state = false;
            alarmEntry.ringId = 1;
            alarmEntry.ringType = 3;
            Log.i("alarm", "编辑闹钟后发送给样机的闹钟序列号 = " + alarmEntry.index);
            boolean lamp = date.isLampState();
            boolean sound = date.isSoundState();
            if (lamp && sound) {
                alarmEntry.title = "2";
            }
            if (!lamp && sound) {
                alarmEntry.title = "0";
            }
            if (lamp && !sound) {
                alarmEntry.title = "1";
            }

            mAlarmManager.remove(alarmEntry);
            mAlarmManager.set(alarmEntry);

        }
        EventBus.getDefault().removeStickyEvent(date);
    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void OnDeleteItem(AlarmDeleteItem date) {
        delete(date);
        setDateList.remove(date.getPosition());
        alarmAdapter.notifyItemRemoved(date.getPosition());
    }

    public void delete(AlarmDeleteItem date) {
        EventBus.getDefault().removeStickyEvent(date);
        BluzManagerData.AlarmEntry alarmEntry = new BluzManagerData.AlarmEntry();
        alarmEntry.index = date.getAlarmIndex();
        Log.i("index", "删除闹钟的序号 = " + alarmEntry.index);
        mAlarmManager.remove(alarmEntry);
    }

    @Override
    public void addViewListener() {
        alarmAdapter.setSwitchCheckListener(new OnSwitchCheckListener() {
            @Override
            public void open(int position) {//开启

//                Log.i("index", "开启闹钟" + position);
                BluzManagerData.AlarmEntry alarmEntry = new BluzManagerData.AlarmEntry();
                Log.i("alarm", "alarmEntry = " + alarmEntry);
                AlarmSetDate alarmSetDate = setDateList.get(position);
                alarmEntry.hour = alarmSetDate.getHour();
                alarmEntry.minute = alarmSetDate.getMinute();
                alarmEntry.repeat = alarmSetDate.getDate();
                alarmEntry.index = alarmSetDate.isIndex();
                Log.i("index", "打開闹钟序列號 = " + alarmEntry.index);
                alarmEntry.state = true;
                alarmEntry.ringId = 1;
                alarmEntry.ringType = 3;
                boolean lamp = alarmSetDate.isLampState();
                boolean sound = alarmSetDate.isSoundState();
                if (lamp && sound) {
                    alarmEntry.title = "2";
                }
                if (!lamp && sound) {
                    alarmEntry.title = "0";
                }
                if (lamp && !sound) {
                    alarmEntry.title = "1";
                }

//                saveIndex(position, alarmEntry.index);
                mAlarmManager.remove(alarmEntry);
                mAlarmManager.set(alarmEntry);


            }

            @Override
            public void close(int position) {//关闭


                BluzManagerData.AlarmEntry alarmEntry = new BluzManagerData.AlarmEntry();
                AlarmSetDate alarmSetDate = setDateList.get(position);
                alarmEntry.hour = alarmSetDate.getHour();
                alarmEntry.minute = alarmSetDate.getMinute();
                alarmEntry.repeat = alarmSetDate.getDate();
                alarmEntry.index = alarmSetDate.isIndex();
                Log.i("index", "关闭闹钟序列號 = " + alarmEntry.index);
                alarmEntry.state = false;
                alarmEntry.ringId = 1;
                alarmEntry.ringType = 3;
                boolean lamp = alarmSetDate.isLampState();
                boolean sound = alarmSetDate.isSoundState();
                if (lamp && sound) {
                    alarmEntry.title = "2";
                }
                if (!lamp && sound) {
                    alarmEntry.title = "0";
                }
                if (lamp && !sound) {
                    alarmEntry.title = "1";
                }
//                saveIndex(position, alarmEntry.index);
                mAlarmManager.remove(alarmEntry);//防止sdk缓存数据 回复不准确（sdk bug）
                mAlarmManager.set(alarmEntry);

            }
        });

        alarmAdapter.setDeleteItemListener(position -> {
            BluzManagerData.AlarmEntry alarmEntry = new BluzManagerData.AlarmEntry();
            alarmEntry.index = setDateList.get(position).isIndex();
            Log.i("idnex", "删除闹钟序列号" + alarmEntry.index);
            mAlarmManager.remove(alarmEntry);
            setDateList.remove(position);
            alarmAdapter.notifyItemRemoved(position);
        });

    }

//    private void saveIndex(int uiPosition, int alarmindex) {
//        if (saveUiIndex != null) {
//            saveUiIndex.clear();
//        }
//        if (saveAlarmIndex != null) {
//            saveAlarmIndex.clear();
//        }
//        saveUiIndex.add(uiPosition);
//        saveAlarmIndex.add(alarmindex);
//    }

    @OnClick({R.id.ib_toset_alarm, R.id.ib_return, R.id.textView3})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ib_toset_alarm:
            case R.id.textView3:
                if (BluzDeviceUtils.getInstance().getConnectionDevice() == null) {
                    showBluetoothDisconnectDialog();
                } else {
                    if (setDateList.size() >= 4) {
                        Toast.makeText(this, "Your alarm clock has reached its maximum limit!!", Toast.LENGTH_SHORT).show();
                    } else {
                        showActivity(SetDataActivity.class);
                    }
                }

                break;
            case R.id.ib_return:
                finish();
                break;
        }

    }


    public void showBluetoothDisconnectDialog() {
        if (!isActivityForeground) {
            return;
        }
        if (disconnectHintDialog == null) {
            disconnectHintDialog = new PromptDialogV2(mContext);
            disconnectHintDialog.setOnButtonClickListener(new PromptDialogV2.OnButtonClickListener() {
                @Override
                public void onPositiveClick() {
                    disconnectHintDialog.dismiss();
                }

                @Override
                public void onNegativeClick() {
                    MainActivity.showActivity(mContext, true);
                    disconnectHintDialog.dismiss();
                }
            });
        }
        disconnectHintDialog.show();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (getIndexGroup != null) {
            getIndexGroup.clear();
        }
        if (setDateList != null) {
            setDateList.clear();
        }
        if (arrayList != null) {
            arrayList.clear();
        }

        Log.i("set", "onDestroy");
    }


}
